import { InjectionKey } from "vue";
import { createStore, Store } from "vuex";
import { login, checkLogin } from "@/api/user"
import { getToken, setToken, removeToken } from '@/utils/auth'
console.log("在 store.ts 中")
export interface RootState {
  token: string;
  isAdmin: boolean;
}
export const key: InjectionKey<Store<RootState>> = Symbol();

const token: string = getToken();

const store = createStore({
  state: {
    token,
    isAdmin: false
  },
  getters: {
    token: (state) => state.token,
    isLogin: (state) => state.token !== "",
    isAdmin: (state) => state.isAdmin,
  },
  mutations: {
    SET_TOKEN(state, payload: string): void {
      if (payload !== "") {
        state.token = payload;
        setToken(payload)
      } else {
        state.token = "";
        removeToken()
      }
    },
    SET_ADMIN(state, flag): void {
      state.isAdmin = flag
    }
  },
  actions: {
    // 用户登录
    async login({ commit }, payload): Promise<string> {
      console.log("enter login:", payload)
      try {
        const res = await login(payload);
        const userToken = res.data.token;
        commit("SET_TOKEN", userToken);
        if (payload.name === "admin") {
          commit("SET_ADMIN", true);
        }
        return userToken;
      } catch (e) {
        return Promise.reject("")
      }
    },
    // 用户登出
    logout({ commit }) {
      removeToken()
      commit("SET_TOKEN", "");
      commit("SET_ADMIN", false);
    },
    //判断jwt是否过期
    async checkAuthState({ commit,dispatch }) {
      console.log("check AuthState")
      const token = getToken() || "";
      if (token !== "") {
        try {
          const res = await checkLogin()
          console.log("有token")
          if (res.data.name === "admin") {
            console.log("是admin")
            commit("SET_ADMIN", true)
          }
          commit("SET_TOKEN", token);
          return res.data.name
        } catch (e) {
          console.log("有token，但已经过期了")
          console.log(e)
          dispatch("logout")
          throw Error("未登录")
        }
      }else{
        throw Error("未登录")
      }
    }
  },
});

// // 初始化时检查一次
// store.dispatch("checkAuthState")

export default store;
